package com.fudan.framework.utils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class JsonUtils {
	private static ObjectMapper mapper = new ObjectMapper();

	static {
		mapper.setSerializationInclusion(Include.NON_NULL);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		ConvertUtils.register(new DateConverter(null), java.util.Date.class);
	}

	public static String toJson(Object obj) throws JsonProcessingException {
		return mapper.writeValueAsString(obj);
	}
	public static <T> T toObject(String value,Class<T> cla) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(value,cla);
	}
	public static <T> T toObject(String value,Type type) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(value,TypeFactory.defaultInstance().constructType(type));
	}
	public static <T> T toObject(String value,TypeReference<T> ref) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(value,ref);
	}
	public static <T> T toObject(Map<String,Object> map,Class<T> clz) throws Exception {
		T t = clz.newInstance();
		BeanUtils.populate(t, map);
		return t;
	}
	public static <T> List<T> toObjectArray(String value,Class<T> cla) throws JsonParseException, JsonMappingException, IOException {
		JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, cla);
		return mapper.readValue(value, javaType);
	}

}
